package com.chaihu.front.service.api.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.base.constants.CommonConstant;
import com.chaihu.core.base.service.front.AppBase;
import com.chaihu.front.service.api.FrontService;
import com.chaihu.utils.constant.ServiceConstant;
import com.chaihu.utils.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author chaihu
 * @date 2021/10/13
 */
@Slf4j
@Service
public class FrontServiceImpl extends AppBase implements FrontService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public ResponseEntity<String> doApi(String body, Map<String, String> headers, HttpServletRequest request) {
        HttpHeaders header = new HttpHeaders();
        log.debug("api请求头" + headers + " == " + header + ";请求内容：" + body);
        HttpMethod method = null;
        String url = ServiceConstant.SERVICE_API_URL + "/api/" + headers.get(CommonConstant.HTTP_SERVICE);
        if (CommonConstant.HTTP_METHOD_POST.equals(headers.get(CommonConstant.HTTP_METHOD))) {
            method = HttpMethod.POST;
        } else if (CommonConstant.HTTP_METHOD_GET.equals(headers.get(CommonConstant.HTTP_METHOD))) {
            method = HttpMethod.GET;
            url += this.mapToUrlParam(JSONObject.parseObject(body));
        } else if (CommonConstant.HTTP_METHOD_DELETE.equals(headers.get(CommonConstant.HTTP_METHOD))) {
            method = HttpMethod.DELETE;
        } else if (CommonConstant.HTTP_METHOD_PUT.equals(headers.get(CommonConstant.HTTP_METHOD))) {
            method = HttpMethod.PUT;
        } else {
            throw new IllegalArgumentException("不支持的请求方式" + headers.get(CommonConstant.HTTP_METHOD));
        }

        for (String key : headers.keySet()) {
            header.add(key, headers.get(key));
        }

        HttpEntity<String> httpEntity = new HttpEntity<String>(body, header);
        log.debug("请求后端url" + url + ",body=" + body + ", header=" + header);
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, method, httpEntity, String.class);
        } catch (HttpStatusCodeException e) { //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常，需要重新封装一下
            ResponseResult result = new ResponseResult(e.getStatusCode()+"", e.getResponseBodyAsString());
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        } catch (Exception e) {
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), e.getMessage());
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        } finally {
            log.debug("api返回信息" + responseEntity);
            return responseEntity;
        }
    }

    @Override
    public ResponseEntity<Object> doResourceApi(String body, Map<String, String> headers, HttpServletRequest request) {
        return null;
    }

}
